properties([
   parameters([
      string(name: 'START_WORK_INDEX', defaultValue: '0', description: ''),
      string(name: 'END_WORK_INDEX', defaultValue: '1', description: ''),
      string(name: 'EXECUTE_NODE', defaultValue: 'master', description: ''),
      choice(name: "PROJECT", choices: ['Test', 'Chijin'], description: 'choose a project'),
      booleanParam(name: 'FIRST_TIME', defaultValue: false, description: 'only prepare for the first time'),
    ])
 ])

node( "${params.EXECUTE_NODE}" )
{
   stage("Prepare")
   {
      if(params.FIRST_TIME)
      {
         def originProjectDir = config.projectDir(params.PROJECT)

         // 挂载Z盘
         bat "if not exist z:\\ ( net use z: ${config.mountDir()} /y )"

         // 拷贝工程到worker
         config.prepareLocalProject(params.PROJECT)

         // 拷贝unity程序
         config.copyUnityDir()

         // 创建log目录
         def logDir = "${originProjectDir}\\${config.distributeLogDir()}"
         bat "if not exist ${logDir} ( mkdir ${logDir} )"
      }
      else
      {
         echo "Only Prepare for The First Time"
      }
   }

   stage('Build: Asset Bundles')
   {
      def originProjectDir = config.projectDir(params.PROJECT)
      // 日志文件
      def logDir = "${originProjectDir}\\${config.distributeLogDir()}"
      def logFile = "${logDir}\\worker-${params.EXECUTE_NODE}-${params.START_WORK_INDEX}-${params.END_WORK_INDEX}${config.buildName()}.log"
      
      // 运行打包程序
      def localProjectDir = config.localProjectDir(params.PROJECT)
      def mainfestFilePath = "${originProjectDir}\\distribute.manifest"
      bat " ${config.localUnityPath()} -quit -batchmode -projectPath ${localProjectDir} -distributedWorker ${mainfestFilePath} ${params.START_WORK_INDEX} ${params.END_WORK_INDEX} -logfile ${logFile}"

      utils.deleteLockFile(params.PROJECT, params.EXECUTE_NODE)
   }
}
